﻿
using System.IO;
using KSS.Generator.Configuration;
using System;
namespace KSS.Generator
{
    public abstract class ProjectGenerator
    {
        private GeneratorContext _context;
        public GeneratorContext Context
        {
            get
            {
                if (_context == null)
                {
                    _context = new GeneratorContext();
                }

                return _context;
            }
            set { _context = value; }
        }

        public abstract string ProjectName
        {
            get;
        }

        /// <summary>
        /// Generate all special template file
        /// </summary>
        /// <param name="projectConfig"></param>
        /// <param name="templateFile"></param>
        /// <param name="generatedDirectory"></param>
        protected abstract void GenerateFile(
                        ProjectSetting projectConfig, 
                        FileInfo templateFile, 
                        DirectoryInfo generatedDirectory);

        public virtual void Generate()
        {
            // find sql schema project settings
            ProjectSetting projectConfig = Context.Setting.GetProjectSetting(ProjectName);

            // Find schema template file
            // Get template directory
            DirectoryInfo templateDirectory = Context.GetTemplateDirectory(projectConfig.TemplateFolderName);
            DirectoryInfo generatedDirectory = new DirectoryInfo(Context.Setting.GeneratedFolderPath + "\\" + projectConfig.ProjectFolderName);

            if (templateDirectory == null || generatedDirectory == null)
            {
                return;
            }

            GenerateDirectory(projectConfig, templateDirectory, generatedDirectory);
        }

        private void GenerateDirectory(ProjectSetting projectConfig,
                        DirectoryInfo templateDirectory,
                        DirectoryInfo generatedDirectory)
        {
            FileInfo[] templateFiles = templateDirectory.GetFiles("*" + Template.TEMPLATE_FILE_EXTENSION, SearchOption.TopDirectoryOnly);

            foreach (FileInfo templateFile in templateFiles)
            {
                GenerateFile(projectConfig, templateFile, generatedDirectory);
            }

            DirectoryInfo[] childTemplateDirectories = templateDirectory.GetDirectories();
            DirectoryInfo childGeneratedDirectory = null;

            foreach (DirectoryInfo childDirectory in childTemplateDirectories)
            {
                childGeneratedDirectory = new DirectoryInfo(generatedDirectory.FullName + "/" + childDirectory.Name);
                GenerateDirectory(projectConfig, childDirectory, childGeneratedDirectory);
            }
        }
    }
}
